package com.lhf.fvsgenerator.config;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.Writer;

/**
 * <p></p>
 *
 * @author lhf
 * @since 2020/10/23 14:43
 */
public class FreeMarkerConfig {

    protected Configuration conf;

    public void write(String templateName, DataModel model, Writer writer) {
        Assert.notNull(writer, "writer 不能为空!!!!");
        try {
            Template template = this.getTemplate(templateName);
            template.process(model, writer);
            writer.flush();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Template getTemplate(String tempName) throws IOException {
        return this.conf.getTemplate(tempName);
    }

    public void setGlobalConf(String name, Object val) throws TemplateModelException {
        Assert.notNull(conf, "conf 不能为空!!!!");
        this.conf.setSharedVariable(name, val);
    }

    @PostConstruct
    public void init() {
        conf.setClassForTemplateLoading(this.getClass(), "templates");
        conf.setDefaultEncoding("utf8");
    }

}


